const path = require("path");
const htmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require("webpack");

const devMode = process.env.NODE_ENV !== "production";

module.exports = {
  mode: process.env.NODE_ENV === "development" ? "development" : "production", // none 、development 、 production
  target: "web",
  entry: "./src/main.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js",
  },
  devtool:
    process.env.NODE_ENV === "development" ? "inline-source-map" : "source-map",
  devServer: {
    port: 8001,
    open: false,
    hot: true,
    https: false,
    // stats: "errors-only",
    // historyApiFallback: false, //不跳转
    after: () => {},
  },
  externals: {
    jquery: "$",
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src/"),
    },
    extensions: [".js", ".vue", ".styl"], // import引入文件的时候不用加后缀
  },
  module: {
    rules: [
      // loader默认从右向左执行
      {
        test: require.resolve("jquery"),
        use: { loader: "expose-loader?$" },
      },
      {
        test: /\.(js|jsx)$/,
        use: { loader: "babel-loader", query: { compact: false } },
        exclude: "/node_modules/",
      },
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
      {
        test: /\.(png|jpe?g|gif|bmp|svg)$/,
        use: [
          {
            loader: "url-loader",
            options: {
              // 配置图片编译路径
              limit: 8192, // 小于8k将图片转换成base64
              name: "img/[name].[hash:7].[ext]",
            },
          },
        ],
      },
      { test: /\.(mp4|ogg|svg)$/, use: ["file-loader"] },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: "url-loader",
        options: {
          limit: 8192,
          name: "fonts/[name].[hash:7].[ext]",
        },
      },
    ],
  },
  plugins: [
    // new webpack.ProvidePlugin({
    //   $: "jquery", // 每个模块注入一个$
    //   "window.jQuery": "jquery", // 每个模块注入一个 window.jQuery
    // }),
    new CleanWebpackPlugin(),
    new htmlWebpackPlugin({
      title: "webpack全实战",
      template: "./public/index.html",
      cdn: {
        css: [],
        js: [
          "https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js", // 配置cdn资源
        ],
      },
    }),
    new webpack.HotModuleReplacementPlugin(),
    new MiniCssExtractPlugin(),
  ],
};
